<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
		<title>赛事</title>
		<link rel="stylesheet" type="text/css" media="screen" href="{$staticHost}/static/css/base.css" />
		<link rel="stylesheet" type="text/css" media="screen" href="{$staticHost}/static/css/competition.css" />
		<script src="{$staticHost}/static/js/jquery-1.8.3.min.js"></script>
		<script src="{$staticHost}/static/js/js.js"></script>
		<script src="{$staticHost}/static/js/mod.js?v=3"></script>
		<style>
			.fixed-apply{
				position: fixed;
				width: 100%;
				background: #fff;
				border-top: 1px solid #dadad8;
			}
			.a02{
				margin-bottom: 2px;
			}
			.list-image>img{
				display: none !important;
			}
			.list-image>img:first-child, .list-image>img:nth-child(2), .list-image>img:nth-child(3){
				display: inline-block !important;
			}
		</style>
	</head>
	<body class="apply-solo">
		<div id="content-solo"></div>
		<script id="solo" type="text/html">
			<h1 class="f18 ac line-gray lh50"><%=result.matchInfo.name%></h1>
			<dl class="solo-info">
				<dt>基本信息</dt>
				<dd>
					<span class="color_gray f15">姓名：</span>
					<input type="text" class='username' name="">
				</dd>
				<dd>
					<span class="color_gray f15">手机号：</span>
					<input type="text" class='userphone' name="" onkeyup="this.value=this.value.replace(/\D/g,'')">
				</dd>
				<dd class="line-gray-bottom">
					<form>
						<span class="color_gray f15">性别：</span>
						<input type="radio" class='male' name="Sex" value="male" />
						<i class="mr10">男</i>
						<input type="radio" class='female' name="Sex" value="female" checked="checked" />
						<i>女</i>
					</form>
				</dd>
			</dl>
			<form>
				<dl class="solo-money">
					<dt>参赛报名</dt>
					<dd <%if(!result.fee_goods_id){%>style="display:none"<%}%>>
						<input type="radio" class='computed applyBtn' name="cost" value="male" />
						<span class="f16">报名费：￥<span class='fee-id'>0</span></span>
						<p class="color-red f13">完成比赛可获得纪念品作为奖励</p>
					</dd>
					<dd class="line-gray-bottom pb10">
						<input type="radio" class='computed' name="cost" value="male" checked/>
						<span class="f16">免费参赛</span>
						<p class="color_gray f13">没有实体奖牌</p>
					</dd>
				</dl>
			</form>
			<!-- 报名信息 -->
			<dl class="line-gray-bottom commodity">
				<dt>纪念品选购</dt>
				<% for(var i = 0; i < result.goodsList.length; i++) { %>
					<% if(result.goodsList[i].id != result.matchInfo.fee_goods_id){ %>
						<dd>
							<span style='display:none;'><%=result.goodsList[i].product.id%></span>
							<span class="chekbox good-id computed"></span>
							<span><%=result.goodsList[i].product.title%></span>
							<div class='list-image'>
								<%if(result.goodsList[i].imageList[i] != 'undefined'){%>
									<% for(var j = 0; j < result.goodsList[i].imageList.length; j++){ %>
										<img src="<%=result.goodsList[i].imageList[j]%>">
									<%}%>
								<%}%>
							</div>
							<a class="color_black f14 rule">选择规格</a>
							<span class="color-blue rule-price">￥0.00</span>
						</dd>
					<%}%>
				<%}%>

			</dl>
			<dl class="line-gray-bottom f14 pb50">
				<dt>报名说明</dt>
				<dd id="trends-explain"><%=result.matchInfo.add_introduce%></dd>
				<dd id="default-explain">
					<p class="lh23">1.请确保填写真实的报名信息。</p>
					2.本活动免费参与，活动结束后将按照活动规则抽取12名幸运用户赠送圣诞周边奖品。
					<p class="lh23">3.本活动的最终解释权归虎扑跑步所有；</p>
				</dd>
			</dl>
			<!-- <a class="line-gray-bottom db p10 f16 color_dgray arrows" href="">纪念品退换规则</a> -->
			<div class="btn-apply fixed-apply">
				合计：￥<span class="color-blue total-price">0.00</span>
				<a class='apply'>报名</a>
			</div>

			<div id="forlogin" class="c-mask" style="display:none ;">
				<section class="imgbig" style="display:none">
					<img src=""/>
				</section>
				<section class="pop-commodity" style="display:none;">
					<span class="close">×</span>

					<dl class='rule-list'>
					</dl>
					<input class="bg_blue color-white f18" id="confirm" type="button" value="确 定"/>
				</section>

			</div>
		</script>
	</body>
	<script src=" https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
	<script>
	var s=0;
	var match_id = "{$match_id}";
	var uid = "{$uid}";

	$(function(){
		$.getJSON('{$staticHost}/matchWeb/matchInfo', {match_id:match_id}, function(data, error) {
			var html = template('solo', data);
			document.getElementById('content-solo').innerHTML = html;

			var rulePrice = document.querySelectorAll('.rule-price');
			var totalPrice = document.querySelector('.total-price');
			var applyFee = document.querySelectorAll('.solo-money>dd>input[type="radio"]');
			var dl = document.querySelector('.solo-money>dl');
			$(".chekbox").click(function(){
				$(this).toggleClass("on");
			})
			$("img").click(function(){
				$('.pop-commodity').hide();
				$("#forlogin").show();
				$(".imgbig").show();
				var big = $(this)[0].src;
				$(".imgbig img").attr("src",big);
			})

			$('#forlogin').click(function(){
				$('#forlogin').hide();
			})

			if(data.result.matchInfo.add_introduce.length>0){
				$("#trends-explain").show();
				$("#default-explain").hide();
			}else{
				$("#trends-explain").hide();
				$("#default-explain").show();
			}
			var ruleArray = [];


			var feeId = data.result.matchInfo.fee_goods_id;
			var goods_ids = data.result.goodsList;
			for(var m = 0; m < goods_ids.length; m++){
				for(var t = 0; t < goods_ids[m].childGoods.length; t++){
					if(feeId == goods_ids[m].childGoods[t].id){
						
						$('.fee-id').html(goods_ids[m].childGoods[t].saleprice);

					}
				}
			}


			var tempArr = [];
			for(var i = 0; i < data.result.goodsList.length; i++){
				
				tempArr.push(data.result.goodsList[i].childGoods[0].saleprice);
			}

			for(var j = 0; j < rulePrice.length; j++){
				rulePrice[j].innerHTML = '$'+tempArr[j];
			}

			// 点击选择规则按钮
			$(".rule").click(function(event){
				$(this).addClass('tag');
				
				var tempId = event.target.parentNode.children[0].innerHTML;
				for(var i = 0; i < data.result.goodsList.length; i++){
					if(tempId == data.result.goodsList[i].product.id){
						var tempArray = data.result.goodsList[i];
						var temp = [];
						var str = '';
						for(var z = 0; z < tempArray.childGoods.length; z++){
							ruleArray.push({
								title: tempArray.childGoods[z].attrPathName,
								price: tempArray.childGoods[z].saleprice
							});
						}

						for (var key in tempArray.attrs){
							str += ('<dt>' + tempArray.attrs[key].headInfo.title + '</dt><dd>');
							for(var n = 0; n < tempArray.attrs[key].attrValue.length; n++){
								
								var attrValue = tempArray.attrs[key].attrValue[n].title;
								var attrId = tempArray.attrs[key].attrValue[n].id;
								str += ('<a class="a02 a'+key+'" data-aid="a'+key+'" data-id="'+attrId+'">' + attrValue + '</a>');
							}
							str += '</dd>,';
						}
						temp = str.split(',');
					}
					$('.rule-list').html(temp);
				}
				$('.imgbig').hide();
				$('#forlogin').show();
				$('.pop-commodity').show();
				$('.pop-commodity').click();
			})

			$('.pop-commodity').click(function(event){
				for(var ai = 1; ai < 50; ai++) {
					$('.a' + ai).on('click', function(){
						$('.' + $(this).attr('data-aid')).removeClass('on');
						$(this).addClass('on');
					});
				}
				event.stopPropagation();
			})

			// ids: 数组中存放商品id
			var ids = [];
			var texts = [];
			// 点击选择规格后的确定按钮
			$('#confirm').click(function(event){
				
				var temp = event.target.parentNode.children[1].children;
				var text = '';
				for(var a = 0; a < temp.length; a++){
						for(var i = 0; i < temp[a].children.length; i++){
							if(temp[a].children[i].className.indexOf('on') > -1){
								text += (temp[a].children[i].innerHTML + ' ');
							}
						}
				}

				var rulePrice2 = '';
				for(var t = 0; t < ruleArray.length; t++){
					
					var newtext = text.split(' ').join('—').slice(0, -1);
					if(ruleArray[t].title.indexOf(newtext) > -1){
						texts.push(ruleArray[t].title);
						rulePrice2 = ruleArray[t].price;
					}
				}
			

				var rules = document.querySelectorAll('.rule');
				for(var i = 0; i < rules.length; i++){
					if(rules[i].className.indexOf('tag') > -1){
						rules[i].innerHTML = text;
						rules[i].nextSibling.nextSibling.innerHTML ='￥'+rulePrice2;
						rules[i].className = 'checkbox on f14 rule';
						var ttemp = rules[i].parentNode.children[1];
						if(ttemp.className.indexOf('on') == -1){
							ttemp.className += ' on';
						}
					}
				}
				$('#forlogin').hide();
				$('.pop-commodity').hide();
				computedTotalFee();
			})

			$('.close').click(function(event){
				var rules = document.querySelectorAll('.rule');
				for(var i = 0; i < rules.length; i++){
					if(rules[i].className.indexOf('tag') > -1){
						var index = rules[i].className.indexOf('tag');
						if(rules[i].className.indexOf('identify') == -1){
							rules[i].className = 'checkbox on f14 rule';
						}
					}
				}
				$('#forlogin').hide();
			})

			// 过滤掉数值中重复的值
			function filterArray(receiveArray){
			var arrResult = new Array();
			    for (var i=0; i<receiveArray.length; ++i) {
			        if(check(arrResult,receiveArray[i]) == -1) {
			            arrResult.push(receiveArray[i]);　
			        }
			    }
			    return arrResult;
			}

			function check(receiveArray,checkItem){
			    var index = -1;
			    for(var i=0; i<receiveArray.length; ++i){
			        if(receiveArray[i]==checkItem){
			            index = i;
			            break;
			            }
			        }
			    return index;
			}

			$('.username').bind('input propertychange', function() {
			    $('.username').css('border', 'none');
			});
			$('.userphone').bind('input propertychange', function() {
			    $('.userphone').css('border', 'none');
			});

			var applyFee = document.querySelectorAll('.solo-money>dd>input[type="radio"]');
			var totalPrice = document.querySelector('.total-price');

			if(data.result.matchInfo.is_free_add == 0){
				applyFee[1].className = '';
				applyFee[1].style.background = '#B6B7BB';
				applyFee[1].checked = false;
				applyFee[1].onclick = function(event){
					return false;
				}

				applyFee[1].parentNode.parentNode.children[2].style.display = 'none';
				$('.solo-money').css('border-bottom', '10px solid #f5f7fa').css('padding-bottom', '20px');
				applyFee[0].checked = true;

				computedTotalFee();
			}

			// 如果childGoods的长度为一，说明里面只有报名费这一个商品，没有其他商品，因此隐藏商品列表区域
			var commodityFor= data.result.goodsList;
			if(commodityFor.length ==0){
				$('.commodity').hide();
			}else if(commodityFor.length==1){
				if(commodityFor[0].product){
					$('.commodity').hide();
				}
				
			}

			// 点击报名
			$('.apply').click(function(){

				if($('.username').val().length == 0){
					$('.username').css('border','1px solid red');
					$('.username').focus();
					return;
				}
				if($('.userphone').val().length == 0){
					$('.userphone').css('border','1px solid red');
					$('.userphone').focus();
					return;
				}

				var mobileReg = /^(17[0-9]|13[0-9]|15[0-9]|18[0-9]|14[57])[0-9]{8,8}$/;
				var phone = $.trim($('.userphone').val());
				if(phone == '' || phone.length != 11 || !mobileReg.test(phone)) {
					alert('手机号码输入有误！请重新输入！');
					return;
				}

				var name = $('.username').val();
				
				var male = document.querySelector('.male');
				var female = document.querySelector('.female');
				var gender = 1; // 性别（默认女）
				if(male.checked){
					gender = 2;
				}else{
					gender = 1;
				}

				var feeId = data.result.matchInfo.fee_goods_id;
				var applyID = document.querySelector('.applyBtn');

				if(applyID.checked){
				
					ids.push(parseInt(feeId));
				}

				
				var url = '{$staticHost}/?c=matchWeb&a=joinMatch';
				var good_ids = document.querySelectorAll('.good-id');

				
				for(var a = 0; a < data.result.goodsList.length; a++){
					for(var b = 0; b < data.result.goodsList[a].childGoods.length; b++){
						var tempText = data.result.goodsList[a].childGoods[b].attrPathName;
						for(var x = 0; x < texts.length; x++){
							if(texts[x].indexOf(tempText) > -1){
								ids.push(data.result.goodsList[a].childGoods[b].id);
							}
						}
					}
				}
				ids = filterArray(ids);
				var goods = ids.toString();
				$.ajax({
					type: 'POST',
					url: '{$staticHost}/matchWeb/joinMatch',
					data: {
						match_id: match_id,
						type: "user",
						name: name,
						phone: phone,
						gender: gender,
                        goods_id: goods
					},
					dataType: 'json',
					success: function(data){
						if(data.status.code == 200){
						
							if(parseFloat($('.total-price').html()) == 0){
								window.location = '{$staticHost}/show/paySuccess?order_id=1&match_id='+match_id;
								// window.location = '{$staticHost}/show/paySuccess';
							}else{
								window.location = "{$goodsDetailUrl}"+"&goods_id="+goods;
							}

						}else{
							alert('报名失败，请稍后再试!!!');
						}
						// window.location = '{$staticHost}/?c=show&a=matchOrderConfirm';
					},
					error: function(error){
						alert('报名失败，请稍后再试！');
					}
				});

			})


			// 计算总价格
			function computedTotalFee(){
				var total = 0;
				if(applyFee[0].checked){
					total = parseFloat($('.fee-id').html());
				}

				for(var i = 0; i < rulePrice.length; i++){
					var checkedOpen = rulePrice[i].parentNode.children[1].className;
					if(checkedOpen.indexOf('on') > -1){
						total += parseFloat(rulePrice[i].innerHTML);
					}
				}
				totalPrice.innerHTML ='￥' +total;
			}

			$('.computed').click(function(){
				computedTotalFee();
			})

			$(".sold .chekbox").unbind();
		})
	});
	$(".chekbox").click(function(){
		$(this).toggleClass("on");
	})
	$("img").click(function(){
		$("#forlogin").show();
		$(".imgbig").show();
		var big = $(this)[0].src
		$(".imgbig img").attr("src",big);
	})
	$(".imgbig").click(function(){
		$(".imgbig").hide();
		$("#forlogin").hide();
	})

	$(".sold .chekbox").unbind();

	</script>

{template 'show/web-footer'}
